﻿@page "/pages/authentication/confirmemail"
@using CleanArchitecture.Blazor.Domain.Identity
@using System.Text
@using Microsoft.AspNetCore.WebUtilities
@using CleanArchitecture.Blazor.Application.Features.Identity.Notifications.SendWelcome

@inject IStringLocalizer<ConfirmEmail> L
@inject UserManager<ApplicationUser> UserManager
@inject IdentityRedirectManager RedirectManager
@inject ILogger<ConfirmEmail> Logger
<PageTitle>@L["Confirm email"]</PageTitle>
<div class="d-flex flex-column gap-y-3">
    <MudText Typo="Typo.h4" GutterBottom="true">@L["Confirm email"]</MudText>
    <StatusMessage Message="@statusMessage" Error="@error"/>
    <a class="mud-button-root mud-button mud-button-text mud-button-text-default mud-button-text-size-medium mud-ripple" href="@Login.PageUrl">@L["Return to Login"]</a>
</div>

@code {
    public const string PageUrl = "/pages/authentication/confirmemail";
    private string? statusMessage;

    [CascadingParameter] private HttpContext HttpContext { get; set; } = default!;

    [SupplyParameterFromQuery] private string? UserId { get; set; }

    [SupplyParameterFromQuery] private string? Code { get; set; }
    private bool error { get; set; }

    protected override async Task OnInitializedAsync()
    {
        if (UserId is null || Code is null)
        {
            RedirectManager.RedirectTo("");
        }

        var user = await UserManager.FindByIdAsync(UserId);
        if (user is null)
        {
            HttpContext.Response.StatusCode = StatusCodes.Status404NotFound;
            statusMessage = string.Format(L["Error loading user with ID {0}"], UserId);
            error = true;
        }
        else
        {
            var code = Encoding.UTF8.GetString(WebEncoders.Base64UrlDecode(Code));
            var result = await UserManager.ConfirmEmailAsync(user, code);
            if (result.Succeeded)
            {
                var callbackUrl = Navigation.GetUriWithQueryParameters(
                    Navigation.ToAbsoluteUri(Login.PageUrl).AbsoluteUri,
                    new Dictionary<string, object?> { ["returnUrl"] = "/" });

                await Mediator.Publish(new SendWelcomeNotification(callbackUrl, user.Email!, user.UserName!));
                Logger.LogInformation("{UserName} Activated Successfully!", user.Email);
                user.IsActive = true;
                await UserManager.UpdateAsync(user);
            }

            statusMessage = result.Succeeded ? L["Thank you for confirming your email."] : L["Error confirming your email."];
            error = result.Succeeded ? false : true;
        }
    }

}